/**
 * @author Isabella Nake (isabella.nake@usi.ch)
 * @author Nicolas Lusa (lusan@usi.ch)
 */
package ch.usi.inf.pf2.gui.action;

import java.awt.event.ActionEvent;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

import ch.usi.inf.pf2.circuit.Input;
import ch.usi.inf.pf2.circuit.Value;
import ch.usi.inf.pf2.gui.CircuitFrame;
import ch.usi.inf.pf2.gui.Model;
import ch.usi.inf.pf2.time.Schedule;
import ch.usi.inf.pf2.time.SetValueOfInputEvent;

public class ResetAction extends AbstractAction {
	
	private static final long serialVersionUID = 1290563839964547139L;
	private Model model;
	private final CircuitFrame circuitFrame;
	
	public ResetAction(final CircuitFrame circuitFrame, final Model model){
		this.circuitFrame = circuitFrame;
		this.model = model;
		putValue(NAME, "Reset");
        final ImageIcon icon = new ImageIcon(getClass().getResource("../icons/reset.png"));
        putValue(SMALL_ICON, icon);
        putValue(SHORT_DESCRIPTION, "Reset the circuit.");
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		reset(circuitFrame, model);
	}
	
	public static void reset(final CircuitFrame circuitFrame, final Model model) {
		Schedule.clearQueue();
		Schedule.resetStep();
		ArrayList<Input> inputs= model.getCircuit().getInputs();
		for(Input input : inputs){
			new SetValueOfInputEvent(Value.UNKNOWN, input, 0);
		}
		Schedule.run();
		Schedule.resetStep();
		circuitFrame.getEditor().removeAll();
		model.shapeChanged();
		for(Input input : inputs){
			String waveform = input.getWaveform();
			for(int i = 0; i < waveform.length(); i++) {
				if(waveform.charAt(i) == '0') {
					new SetValueOfInputEvent(Value.FALSE, input, i);
				} else {
					new SetValueOfInputEvent(Value.TRUE, input, i);
				}
				
			}
			circuitFrame.setEditor(new JLabel(input.getName() + ": " + input.getWaveform()));
//			input.getLabel().setText(input.getName() + ": " + input.getWaveform());
//    		circuitFrame.setEditor(input.getLabel());	
		}
    	circuitFrame.getEditor().revalidate();
	}

}
